<?php

!defined("DYNAMIC_TABLE")?define("DYNAMIC_TABLE","phome_jatdynamic"):'';




//---------------------------用户自定义标签函数文件
function image_resize($f,$tw,$th,$w_x,$w_y,$string,$font_size,$color_r,$color_g,$color_b){
//$tw - 宽度
//$th - 高度
//$w_x -位置x轴
//$w_y -位置y轴
//font-size 字体大小
//color 颜色RGB
        $temp = array(1=>'gif', 2=>'jpeg', 3=>'png');
        $t=$f;
        list($fw, $fh, $tmp) = getimagesize($f);
        if(!$temp[$tmp]){
                return false;
        }
        
        $tmp = $temp[$tmp];
        $infunc = "imagecreatefrom$tmp";
        $outfunc = "image$tmp";
        $fimg = $infunc($f);
        
                if($fw/$tw > $fh/$th){
                        $fw = $tw * ($fh/$th);
                }else{
                        $fh = $th * ($fw/$tw);
                }
        
                $timg = imagecreatetruecolor($tw, $th);
                $color=imagecolorallocate($timg,$color_r,$color_g,$color_b);
                imagecopyresampled($timg, $fimg, 0,0,0,0, $tw,$th, $fw,$fh);
                imagestring($timg,$font_size,$w_x,$w_y,$string,$color);
                if($outfunc($timg, $t)){
                        return true;
                }else{
                        return false;
                }
        }
 function setUserTags($post){
	 global $empire,$user_userid,$user_tablename;
	$user=islogin();
	$user_id=$user[userid];
	$tag=$post['tags'];
	$sql=$empire->query("update {$user_tablename} set tags ='$tag' where ".$user_userid."='$user_id'");
	if($sql){
		sendNews(SET_TAGS_ID,0,0,array('userid'=>$user_id));
		ajaxMessage('编辑成功！',1);
	}else{
		ajaxMessage('执行失败',0);
	}
	return $sql;
 }
 function addMyNews($type_id,$id='',$subType='',$otherParam=array()){	
	global $empire,$user_userid,$user_tablename;
	$uid=$otherParam['uid'];	
	!defined("DYNAMIC_TABLE")?define("DYNAMIC_TABLE","phome_jatdynamic"):'';
	if(!$uid){$uid= intval(getcvar('mluserid'));}
	$info=getOnLineSayType($type_id);
	$tableName=$info['tb'];	
	$id_field_str=$info[id_field]?$info[id_field]:"id";	
	$fields=$info['fields']?$info['fields']:"*";	
	
	if(is_string($id)||is_int($id)){
		$app_id=$id;
		$app_sql="SELECT $fields FROM $tableName WHERE $id_field_str='$app_id'";//提取源信息；
		$toAddArr=$empire->fetch1($app_sql);		
		if(!is_array($toAddArr)){
			return false;
		}
	}elseif(is_array($id)){
		$toAddArr=$id;
		$app_id=$r[$id_field_str];
	}else{
		return false;
	}
	$recent_sql="SELECT * FROM ".DYNAMIC_TABLE." WHERE uid='$uid' AND type_id='$type_id'";
	$recent_sql.=$subType?" AND sub_type='{$subType}'":"";	
	$recent_sql.=(" ORDER by time desc");
	$od=$empire->fetch1($recent_sql);

	$length=0;
	$waitArr=array();
	
	if($od){
		$jod=jat_decode(($od['data']),true);		
		if(is_array($jod)){
			foreach($jod as $ky=>$vl){
				if(is_array($otherParam['sameFieldArr'])){
					$is_have_same=isSameArray($otherParam['sameFieldArr'],$vl);
				}else{			
					$is_have_same=($vl[$id_field_str]==$app_id);
				}
				if(!$is_have_same){
					$waitArr[]=$vl;
				}
			}
		}
		array_unshift($waitArr,$toAddArr);
	}else{
		$waitArr[]=$toAddArr;
	}			
	$oid=$od['id'];
	if($od){
		if(($info["item_length"]?(count($waitArr)<=$info["item_length"]):true)){
			$isEdit=true;		
			$d=(jat_encode($waitArr));
		}else{
			$d=(jat_encode($toAddArr));
			$isEdit=false;
		}
	}else{
		$d=(jat_encode($waitArr));
		$isEdit=false;
	}	
	
	if($isEdit && $oid){
		$sql_update="UPDATE ".DYNAMIC_TABLE." SET recently_app_id=$app_id,data='$d',time='".time()."' WHERE id='$oid'";	
		$flag=$empire->query($sql_update);

	}else{
		$sql_save="INSERT INTO ".DYNAMIC_TABLE."(uid,recently_app_id,data,type_id,sub_type,time) VALUES($uid,$id,'$d',$type_id,'{$subType}',".time().")";			
		$flag=$empire->query($sql_save);
	}	
	return true;
 }
function sendNews($type_id,$sub_type=0,$sub_type_1=0,$_p=array()){
	global $lguserid;
	!defined("DYNAMIC_TABLE")?define("DYNAMIC_TABLE","phome_jatdynamic"):'';
	$app_user_id=$_p['uid']?$_p['uid']:$lguserid;
	$typeDATA=getOnLineSayType($type_id);
	if(empty($typeDATA)){
		return false;
	}
	$_IDF_=$typeDATA['id_field'];
	$_TB_=$typeDATA['tb'];
	$_TF_=$typeDATA['fields'];
	$T_DATA=$_p['T_DATA']?$_p['T_DATA']:DbTouch($_TB_,array($_IDF_=>$_p[$_IDF_]),$_TF_);
	$_ID_=$T_DATA[$_IDF_];
	$rs=DbTouch(DYNAMIC_TABLE,array('uid'=>$app_user_id,'type_id'=>$type_id,'sub_type'=>$sub_type,'sub_type_o'=>$sub_type_1));		
	if($rs){
		$tArr=jat_decode($rs['data']);
		if(is_array($tArr)){
			$buildArr=array();
			foreach($tArr as $k=>$v){
				if($tArr[$_IDF_]==$_ID_){
					continue;
				}
				$buildArr[$k]=$v;
			}
			array_unshift($buildArr,$T_DATA);
			
			$length=(int)($typeDATA[item_length]?$typeDATA[item_length]:5);			
			if(count($buildArr)>$length){$buildArr=@array_slice($buildArr,0,$length);}
			$time=time();			
		}else{
			$buildArr=$T_DATA;
		}		
			dbEdit(DYNAMIC_TABLE,array(										
								'recently_app_id'=>$_ID_,
								'data'=>jat_encode($buildArr),							
								'update_time'=>time(),						
						),array('id'=>$rs['id']));

	}else{
		$buildArr=$T_DATA;
		$time=time();
		dbAdd(DYNAMIC_TABLE,array(		'uid'=>$app_user_id,
										'recently_app_id'=>$_ID_,
										'data'=>jat_encode($buildArr),
										'type_id'=>$type_id,
										'sub_type'=>$sub_type,
										'sub_type_o'=>$sub_type_1,
										'update_time'=>$time,
										'time'=>$time
								));
	}
	return true;
		
}
function getUserOnLineList($uids,$type='',$subType='',$length='10'){
	if(1){
	global $empire,$user_userid,$user_tablename;
	$sql="SELECT * FROM ".DYNAMIC_TABLE." WHERE ";
	$sql=$uids?($sql." uid in ($uids) "):($sql." 1 "); 	
	$sql.=($type?" AND type_id='{$type}'":"").($subType?" AND sub_type='{$subType}'":"");
	
	$sql.=" order by update_time  desc";
	$sql.= " limit $length";	
	$source=$empire->query($sql);
	$rtn=array();

	while($r=$empire->fetch($source)){		
		$r["data"]= jat_decode($r["data"]);
		$all[]=$r;
		//$rtn[]=$r["data"];
	}
	//var_dump($rtn);
	//print_r($all);
	return ($all);
	}else{
		return false;
	}
}
/**
*
*添加直播
**/
function addSay($array,$dataFromType){
	global $empire;
	$uid= intval(getcvar('mluserid'));
	if(!$uid){
		show_msg("用户未登录或长久未动作！",-1);
	}elseif(!$array['text']){
		show_msg("内容不能为空！",-2);
	}
	$i=getOnLineSayType(SAY_TYPE_ID);
	$sql="INSERT INTO {$i['tb']}(userid,title,time) values('{$uid}','{$array['text']}','".time()."')";	
	$f=$empire->query($sql);
	if(!$f){
		show_msg("系统错误，error:".__LINE__,0);
	}
	$id=mysql_insert_id();
	
	sendNews(SAY_TYPE_ID,0,0,array('id'=>$id));
	DbAddOne("phome_enewsmember",array("userid"=>$uid),"live_num");//我的直播用户字段加一；
	show_msg("添加成功！",1);
}
function getOnLineSayType($type){
	$arr=array(
				SAY_TYPE_ID=>array(
									"tb"=>"phome_jatsay",
									"id_field"=>"id",
									"fields"=>"id,userid,title,time",
									"item_length"=>1
							),//直播
				SET_TAGS_ID=>array(
									"tb"=>"phome_enewsmember",
									"id_field"=>"userid",
									"fields"=>"userid,tags,'".time()."' as time",
									"item_length"=>5
									),//修改标签
				CHG_HEAD_ID=>array(
									"tb"=>"phome_enewsmemberadd",
									"id_field"=>"userid",
									"fields"=>"userid,userpic,'".time()."' as time",
									"item_length"=>1
									),//修改头像；
				ADD_FOCUS_ID=>array(
									"tb"=>"phome_jat_focus",
									"id_field"=>"id",
									"fields"=>"*",
									"item_length"=>2
									),//关注某人；
				JOIN_TRIBE_ID=>array(
									'tb'=>'phome_ecms_tribe',
									'id_field'=>'id',
									"fields"=>"id,classid,title,cover_url,province,city",
									'item_length'=>1,
								
								),//加入了圈子；
				);
	return $arr[$type];
}
function jat_encode($arr,$is_first=true){
	//print_r($arr);
	return serialize($arr);
	if(is_array($arr)){
		$rtn=array();
		foreach($arr as $key=>$value){
			if(is_array($value)){
				$rtn[$key]=jat_encode($value,false);
			}else{
				$rtn[$key]=urlencode($value);
			}
		}
		if($is_first){
			return json_encode($rtn);
		}else{
			return ($rtn);
		}
	}else{
		return $arr;
	}
}
//echo urldecode("%E5%8F%91%E5%B8%83 ");
function jat_decode($arr,$isjson=true){
	return unserialize($arr);
	if($isjson){
		$arr=json_decode($arr,true);
		//print_r($arr);
	}
	if(is_array($arr)){
		$rtn=array();
		foreach($arr as $key=>$value){
			if(is_array($value)){			
				$rtn[$key]=jat_decode($value,false);
			}else{	
				$rtn[$key]=$value?urldecode($value):$value;				
			}
		}
		//print_r($rtn);
		return ($rtn);
	}else{//echo __LINE__;
		return urldecode($arr);
	}
}

function getMyFocusUids($uid='',$haveMy=true){
	global $empire;	
	if(!$uid){$uid= intval(getcvar('mluserid'));}	
	$s="select * from phome_jat_focus where uid = '{$uid}' AND type_id='".USR_FOCUS_ID."'";	
	$source=$empire->query($s);
	$rt=array();
	while($r=$empire->fetch($source)){		
		$rt[]=$r['t_uid'];
	}
	if($haveMy){
		array_unshift($rt,$uid);
	}
	return implode(",",$rt);
}
function show_msg($msg,$flag=false){
	if($flag!==false){
		$array=array("flag"=>$flag,"msg"=>$msg);
		echo json_encode($array);
		exit();
	}
}
function qtime($time){
       $limit = time() - $time;
 
       if($limit<60)
       $time="{$limit}秒前";
       if($limit>=60 && $limit<3600){
            $i = floor($limit/60);
            $_i = $limit%60;
            $s = $_i;
           $time="{$i}分{$s}秒前";
       }
       if($limit>=3600 && $limit<3600*24){
            $h = floor($limit/3600);
            $_h = $limit%3600;
            $i = ceil($_h/60);
            $time="{$h}小时{$i}分前";
       }
       if($limit>=(3600*24) && $limit<(3600*24*30)){
            $d = floor($limit/(3600*24));
            $time= "{$d}天前";
        }
		if($limit>=(3600*24*30)){
            $time=gmdate('Y年n月j日', $time);
        }
		return $time;
}
function addFocusUser($param){
	global $empire;	
	$t_uid=$param['tuid'];
	$uid= intval(getcvar('mluserid'));
	$is_focus=$_REQUEST["is_focus"];
	$sl="SELECT COUNT(id) as num FROM phome_jat_focus WHERE uid='$uid' AND t_uid='$t_uid' AND type_id='".USR_FOCUS_ID."'";	
	$r=$empire->fetch1($sl);
	if($is_focus){
			$s="delete from phome_jat_focus WHERE uid='$uid' AND t_uid='$t_uid' AND type_id='".USR_FOCUS_ID."' limit 1";
			DbLessOne("phome_enewsmember",array("userid"=>$uid),"focus_num");
			DbLessOne("phome_enewsmember",array("userid"=>$t_uid),"focused_num");
			$empire->query($s);
			show_msg("ok",1);
	}else{
		if($r['num']!=0){
			show_msg("已经关注过，不能再次关注！",-1);
		}else{			
			$s="INSERT INTO phome_jat_focus(uid,t_uid,time,type_id,status)VALUES('$uid','$t_uid','".time()."','".USR_FOCUS_ID."','1')";
			$empire->query($s);
			$id=mysql_insert_id();
			//addMyNews(ADD_FOCUS_ID,$id,USR_FOCUS_ID,array("sameFieldArr"=>array("uid"=>"$uid","t_uid"=>"$t_uid")));//添加关注；
			
			sendNews(ADD_FOCUS_ID,$t_uid,0,array('id'=>$id));
			DbAddOne("phome_enewsmember",array("userid"=>$uid),"focus_num");//我的直播用户字段加一；
			DbAddOne("phome_enewsmember",array("userid"=>$t_uid),"focused_num");//我的直播用户字段加一；
			show_msg("ok",1);
		}
	}
}
function addFocus($data,$type){
	
}
function getUserHead($path,$w='',$h=''){
	global $public_r;
	if($path){
		$rp=preg_replace("/_[\d]*_[\d]*\.([\w]{1,4})$/","_{$w}_{$h}.\$1",$path);
		return $rp;
	}else{
		return $public_r[newsurl].'e/data/images/nouserpic.gif';
	}
}
function getImgSizeUrl($path,$w='',$h='',$defaultUrl=''){
	global $public_r;
	if($path){
		$rp=preg_replace("/_[\d]*_[\d]*\.([\w]{1,4})$/","_{$w}_{$h}.\$1",$path);
		if($rp==$path){
			$rp=preg_replace("/\.([\w]{1,4})$/","_{$w}_{$h}.\$1",$path);
			if(is_file($rp)){
				return $rp;
			}else{
				return $rp;
			}
		}else{
			return $rp;
		}		
	}else{
		return $defaultUrl;//$public_r[newsurl].'e/data/images/nouserpic.gif';
	}
}
function rebuildHtml(){
	$url=dirname(dirname($_SERVER["SCRIPT_URI"]));
	$url=$url."/admin/ecmschtml.php?enews=ReIndex&nologin=1";	
	$content=@file_get_contents($url);
}
/**
*$data:
*$fd 排重字段；
**/
function DbDataAddOrEdit($tb,$data,$fd=false){
	global $empire;	
	$sql="SELECT count(*) as num from {$tb} where ";
	if($fd && is_array($fd)){			
		$sql=$sql.getSqlString($fd,"AND");
		$r=$empire->fetch1($sql);
	}else{
		//return false;
	}	
	
	if($r["num"]==1){
		$sql2="UPDATE {$tb} set ".getSqlString($data,",")." WHERE ".getSqlString($fd,"AND");
		$atype="edit";
	}else if($r["num"]==0){
		$atype="add";
		$newArr=is_array($fd)?array_merge($data,$fd):$data;
		//$extendSql=getSqlString($fd,",");
		$sql2="INSERT INTO {$tb} set ".getSqlString($newArr,",");//.($extendSql?(",".$extendSql):"");		
	}else{
		return false;
	}	
	if($empire->query($sql2)){
		return $atype;
	}else{
		return false;
	}	
}
function DbEdit($tb,$data,$one){
	global $empire;	
	if(DbTouch($tb,$one)){
		//$newArr=is_array($one)?array_merge($data,$one):$data;
		$newArr=$data;
		$sql2="UPDATE {$tb} set ".getSqlString($newArr,",")." WHERE ".getSqlString($one,"AND");		
		if($empire->query($sql2)){
			return true;
		}else{
			return false;
		}	
	}else{
		return false;
	}
}
function DbDelete($tb,$one){
	global $empire;	
	if(true || DbTouch($tb,$one)){
		//$newArr=is_array($one)?array_merge($data,$one):$data;
		$newArr=$data;
		$sql2="DELETE FROM {$tb} WHERE ".getSqlString($one,"AND");	
	
		if($empire->query($sql2)){
			return true;
		}else{
			return false;
		}	
	}else{
		return false;
	}
}
function DbAdd($tb,$data){
	global $empire;	
	if(is_array($data) && $tb){
		$sql2="INSERT INTO {$tb} set ".getSqlString($data,",");
		if($empire->query($sql2)){			
			return mysql_insert_id();
		}else{
			return false;
		}	
	}else{
		return false;
	}
}
function DbTouch($tb,$arr,$field="*",$otherStr=''){
	global $empire;	
	$sql="SELECT {$field} FROM {$tb} WHERE ".getSqlString($arr,"AND")." ".$otherStr;	
	//echo $sql;	
	$r=$empire->fetch1($sql);		
	//var_dump($r);
	return 	$r;
}
function DbTouchAll($tb,$arr,$field="*",$otherStr=''){
	global $empire;	
	$sql="SELECT {$field} FROM {$tb} WHERE ".getSqlString($arr,"AND")." ".$otherStr;
	$infosql=$empire->query($sql);
	$index=0;
	while($ri=$empire->fetch($infosql)){
		$r[$index++]=$ri;
	}
	return 	$r;
}
function DbAddOne($tb,$one,$field){
	global $empire;	
	if(DbTouch($tb,$one)){
		$sql2="UPDATE {$tb} set ".$field."=$field+1 WHERE ".getSqlString($one,"AND");		
		//echo $sql2;
		if($empire->query($sql2)){
			return $atype;
		}else{
			return false;
		}	
	}else{echo __LINE__;
		return false;
	}
}
function DbLessOne($tb,$one,$field){
	global $empire;	
	if(DbTouch($tb,$one)){
		$sql2="UPDATE {$tb} set ".$field."=$field-1 WHERE ".getSqlString($one,"AND");
		if($empire->query($sql2)){
			return $atype;
		}else{
			return false;
		}	
	}else{
		return false;
	}
}
function getSqlString($arr,$type=''){
	if(is_array($arr)){		
		/**/foreach($arr as $key=>$val){
			$con.=(" $type ".$key."='".$val."'");
		}
		$len=(strlen($type)+1);		
		$extend=substr($con,$len);
		return $extend;
	}else{
		return false;
	}
}
function emptyArrayTest($arr,$akey){
	foreach($akey as $key=>$val){
		if(array_key_exists($val,$arr)){
			if(empty($arr[$val])){
				return false;
			}
		}else{
			return false;
		}
	}
	return true;
}
function enSafeContent($str){
	$str=str_replace(">","》",($str));
	$str=str_replace(">","《",($str));
	$str=addslashes($str);
	return $str;
}
function isSameArray($s,$t,$absoluty=false){
	if($absoluty && count($s)!=count($t)){
		return false;
	}elseif(is_array($s) && is_array($t)){
		foreach($s as $k=>$v){
			if($v!=$t[$k]){
				return false;
			}
		}
		return true;
	}else{
		return false;
	}	
}
function deSafeContent($str){
	//$str=str_replace(">","》",($str));
	//$str=str_replace(">","《",($str));
	$str=stripslashes($str);
	return $str;
}
function getPics($file,$arrPic,$isRepalce=false){

if(is_array($arrPic)){
		foreach($arrPic as $kp=>$vp){
			$wh=explode("_",$vp);
			$fileInfo=pathinfo($file);	
			//echo $r_small;
			$pws=$arrPos[$kp]?$arrPos[$kp]:"150_40";
			$pwh=@explode("_",$pws);
			$pw=($pwh[0]?$pwh[0]:150)."px";
			$ph=($pwh[1]?$pwh[1]:40)."px";
			if($isRepalce!==false && $isRepalce==$kp){
				$tname=$file;
			}else{
				$tname=str_replace(".{$fileInfo['extend']}","_{$wh[0]}_{$wh[1]}.{$fileInfo['extend']}",$file);
				@copy($file,$tname);				
			}			
			image_resize($tname,"{$wh[0]}","{$wh[1]}","{$pw}","{$ph}","",3,0,0,0);
		}
	
	}else{
		return false;
	}
}
function list_act_vote($id){
	
}
function get_vote_data($d,$name='votetext'){
	global $empire,$public_r,$dbtbpre;
	$r_exp="\r\n";
	$f_exp="::::::";
	$r_r=explode($r_exp,$d);
	$rt=array();
	for($i=0;$i<count($r_r);$i++){
		$checked++;
		$f_r=explode($f_exp,$r_r[$i]);
		$rt[]=array('title'=>$f_r[0],"num"=>$f_r[1],'name'=>$name);				
    }
	return $rt;
}
function list_vote_html($d,$tagname='td',$class=0){
	if(is_array($d)){
		foreach($d as $k=>$v){
			$name=$v['name'];
			//$v=$v['name'];
			$text=$v['title'];
			$kv=$k+1;
			if($r[voteclass])
			{$vote.="<$tagname><input type=checkbox name={$name}[] value='".$kv."' />$text</$tagname>";}
			else
			{$vote.="<$tagname><input type=radio name={$name} value='".$kv."' />$text</$tagname>";}
		}
		return $vote;
	}else{
		return false;
	}
}function jatGetVoteInfo($id){
	$d=DbTouch('phome_enewsinfovote',array("id"=>$id));
	if(empty($d)){return false;}
	$i[]=jatGetVoteArea($d['votetext']);
	$i[]=jatGetVoteArea($d['vote1_text']);
	$i[]=jatGetVoteArea($d['vote2_text']);
	$i[]=jatGetVoteArea($d['vote3_text']);
	$i[]=jatGetVoteArea($d['vote4_text']);
	return $i;
}
function jatGetVoteArea($text){
	$VoteField="::::::";
	$VoteRecord="\r\n";
	$vote_r=explode($VoteRecord,$text);
	if(is_array($vote_r)){
		foreach($vote_r as $k=>$v){
			$a=explode($VoteField,$v);
			$rt[]=array('title'=>$a[0],'num'=>$a[1]);
		}
	}
	return $rt;
}
/**积分制投票的数据**/
function getVoteTotalFen($arr){
	$rtn=0;
	$length=0;
	foreach($arr as $k=>$v){
		$length=$length+$v['num'];
		$rtn=$rtn+(($k+1)*20)*$v['num'];
	}
	$total=$length*20;	
	return @number_format($rtn/$total,1);
}
/**积分制投票的数据**/
function getVoteTotalNum($arr){
	$rtn=0;
	$length=0;
	foreach($arr as $v){
		$rtn=$rtn+($v['num']);
	}	
	return $rtn;
}
/** add by jat**/
function jatAddVoteArea($text,$selectedIndex){
	$VoteField="::::::";
	$VoteRecord="\r\n";
	if(empty($text)){
			return false;
	}
	$vote_r=explode($VoteRecord,$text);

	$v_r=explode($VoteField,$vote_r[$selectedIndex-1]);
	if(empty($v_r[0]))
	{
		return false;
	}
	$vote_num=$v_r[1]+1; 
	$vote_r[$selectedIndex-1]=$v_r[0].$VoteField.$vote_num;
	$new_vote_total=1;
	for($n=0;$n<count($vote_r);$n++)
		{
			$new_votetext.=$vote_r[$n].$VoteRecord;
		}
	$new_votetext=substr($new_votetext,0,strlen($new_votetext)-2);//去掉最后的字符
	return $new_votetext;
}
//退出部落
function exitTribe($uid,$tribe_id){
	global $public_r;
	//if(DbTouch('phome_jat_jointribe',array('uid'=>$uid,'tid'=>$tribe_id))){
		DbDelete('phome_jat_jointribe',array('uid'=>$uid,'tid'=>$tribe_id));
	//}
	//header('Location:-1');
}
?>